package datastructure.turnprint;

/**
 * @Author ZhangCuirong
 * @Date 2025/7/30 14:22
 * @description: 三个线程轮流打印
 */
public class PrintNumber1 {
    private int num = 0;
    private final int Max = 200000;

    public void print(int order) {
        while (num < Max) {
            synchronized (this) {
                while (num < Max && num % 3 != order) {//这里不判断会死等
                    try {
                        this.wait();
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                        return;
                    }
                }
                //双重检查
                if (num < Max) {
                    System.out.println(Thread.currentThread().getName() + " : " + num);
                    num++;
                    this.notifyAll();
                } else {
                    this.notifyAll(); // 唤醒其他线程，避免死等
                    break;
                }
            }
        }
    }

    public static void main(String[] args) {
        PrintNumber1 printNumber = new PrintNumber1();
        Thread thread1 = new Thread(() -> {
            printNumber.print(0);
        }, "A");
        Thread thread2 = new Thread(() -> {
            printNumber.print(1);
        }, "B");
        Thread thread3 = new Thread(() -> {
            printNumber.print(2);
        }, "C");
        thread1.start();
        thread2.start();
        thread3.start();
    }

}
